package com.yingdong.robot;

import java.io.UnsupportedEncodingException;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.Channel;

public class RobotMessage {
	private ByteBuf buffer;
	private int opcode;

	public ByteBuf getBuffer() {
		return buffer;
	}

	public void setBuffer(ByteBuf buffer) {
		this.buffer = buffer;
	}

	public int getOpcode() {
		return opcode;
	}

	public void setOpcode(int opcode) {
		this.opcode = opcode;
	}

	public RobotMessage(int opcode) {
		super();
		this.opcode = opcode;
		this.buffer = ByteBufAllocator.DEFAULT.buffer();
		this.buffer.writeShort(127);
		this.buffer.writeShort(0);
		this.buffer.writeInt(opcode);
	}

	public RobotMessage writeByte(int value) {
		buffer.writeByte(value);
		return this;
	}

	public RobotMessage writeInt(int value) {
		buffer.writeInt(value);
		return this;
	}

	public RobotMessage writeShort(int value) {
		buffer.writeShort(value);
		return this;
	}

	public RobotMessage writeLong(long value) {
		buffer.writeLong(value);
		return this;
	}

	public RobotMessage writeFloat(float value) {
		buffer.writeFloat(value);
		return this;
	}

	public RobotMessage writeDouble(double value) {
		buffer.writeDouble(value);
		return this;
	}

	public RobotMessage writeString(String value) {
		byte[] bytes;
		try {
			bytes = value.getBytes("utf8");
			int len = bytes.length;
			buffer.writeShort(len);
			buffer.writeBytes(bytes);
			return this;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return null;
		}

	}

	public void sendToServer(Channel channel) {
		buffer.readerIndex(0);
		int len = buffer.readableBytes();
		buffer.setShort(0, 127);
		buffer.setShort(2, len);
		channel.writeAndFlush(buffer);
	}
}
